package org.madgecko.api.controller;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.madgecko.basic.model.AjaxReturn;
import org.madgecko.api.model.Message;
import org.madgecko.api.model.enumeration.MessageCategory;
import org.madgecko.api.service.iface.IMessageService;
import org.madgecko.basic.model.Pager;
import org.madgecko.basic.model.SystemContext;
import org.madgecko.common.enumeration.Status;
import org.madgecko.common.util.Base64Tools;
import org.madgecko.web.PropertyHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author       : MadFrog
 * Date         : 2018/11/10 12:48
 * Description  : 消息控制器
 */
@Controller
public class MessageController {

    private static final int PREVIEW_WIDTH = 640;
    private static final int THUMB_WIDTH = 100;
    private static final int THUMB_HEIGHT = 80;

    @Autowired
    private IMessageService messageService;

    @RequestMapping(value = "/admin/news/create/page", produces={"application/json; charset=UTF-8"})
    public String go2AddPage() {
        return "admin/message/create";
    }

    @ResponseBody
    @RequestMapping(value = "admin/message/create", produces={"application/json; charset=UTF-8"})
    public AjaxReturn create(Message message) {
        message.setStatus(Status.ENABLED);
        message.setCreateDate(new Date());
        messageService.add(message);
        return new AjaxReturn(true, "添加成功");
    }

    /**
     *
     * 上传预览图片
     * @param preview
     * @param resp
     */
    @Deprecated
    @RequestMapping(value = "admin/message/preview/upload")
    public void previewUpload(MultipartFile preview, HttpServletResponse resp) {
        try {
            String originalName = preview.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            Date currentDate = new Date();
            //TODO 保存到虚拟路径
            String day = new SimpleDateFormat("yyyyMMdd").format(currentDate).toString();
            String orgFileName = SystemContext.getSystemPath() + "/resources/upload/images/" + day + "/original_" + currentDate.getTime() + "." + extension;
            String previewFileName = SystemContext.getSystemPath() + "/resources/upload/images/" + day + "/preview_" + currentDate.getTime() + "." + extension;
            String iconName = "/api/resources/upload/images/" + day + "/icon_" + currentDate.getTime() + "." + extension;
            String iconFileName = SystemContext.getSystemPath() + "/resources/upload/images/" + day + "/icon_" + currentDate.getTime() + "." + extension;
            FileUtils.copyInputStreamToFile(preview.getInputStream(), new File(orgFileName));

            BufferedImage bi = null;
            bi = ImageIO.read(preview.getInputStream());
            int originalWidth = bi.getWidth();
            Thumbnails.Builder<BufferedImage> bf = Thumbnails.of(bi);
            //图片宽度超过上限,需按比例缩小
            if(originalWidth > PREVIEW_WIDTH){
                bf.scale((double)PREVIEW_WIDTH/(double)originalWidth);
            }else{
                bf.scale(1.0f);
            }
            bf.toFile(previewFileName);
            //压缩至缩略图的1.2倍
            double scale = (double)(THUMB_WIDTH*1.2)/(double)originalWidth;
            BufferedImage thumbBi = Thumbnails.of(bi).scale(scale).asBufferedImage();
            Thumbnails.of(thumbBi).scale(1.0f)
                    .sourceRegion(Positions.CENTER, THUMB_WIDTH, THUMB_HEIGHT)
                    .toFile(iconFileName);
            resp.getWriter().write(iconName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "admin/message/snapshoot/upload", produces={"application/json; charset=UTF-8"})
    public AjaxReturn uploadSnapshoot(String imageData) {
        Date currentDate = new Date();
        //TODO 保存到虚拟路径
        // 获取真实路径
        String webAttachPath = PropertyHolder.getProperty("config.webAttachPath");
        String contextPath = PropertyHolder.getProperty("config.contextPath");
        String day = new SimpleDateFormat("yyyyMMdd").format(currentDate).toString();
        long time = currentDate.getTime();
        String fileName = "preview_" + time + ".png";
        String dirPath = webAttachPath + "/upload/images/" + day;
        String dbPath = "/" + contextPath + "/resources/upload/images/" + day + "/" + fileName;
        Base64Tools.decodeToFile(imageData, dirPath, fileName);
        return new AjaxReturn(true, dbPath, "上传成功");
    }

    @ResponseBody
    @RequestMapping(value = "admin/message/delete/{id}", produces={"application/json; charset=UTF-8"})
    public AjaxReturn listByCategory(@PathVariable Integer id) {
        messageService.delete(id);
        return new AjaxReturn(true);
    }

    @ResponseBody
    @RequestMapping(value = "message/list", produces={"application/json; charset=UTF-8"})
    public AjaxReturn listByCategory(MessageCategory category) {
        return new AjaxReturn(true, messageService.listByCategory(category));
    }

    /**
     *
     * 分页参数名称为start
     * start代表的是要显示的页码上面的第一个条目在总条目中的index（也就是排第几个）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "message/find", produces={"application/json; charset=UTF-8"})
    public AjaxReturn find(MessageCategory category) {
        Pager<Message> pager = messageService.find(category);
        return new AjaxReturn(true, pager.getDatas(), pager.getTotal());
    }

    @RequestMapping(value = "message/display/{id}", produces={"application/json; charset=UTF-8"})
    public String display(@PathVariable Integer id, Model model){
        Message message = messageService.load(id);
        model.addAttribute(message);
        return "displayMessage";
    }

    @ResponseBody
    @RequestMapping(value = "message/load/{id}", produces={"application/json; charset=UTF-8"})
    public AjaxReturn load(@PathVariable Integer id){
        Message message = messageService.load(id);
        return new AjaxReturn(true, message);
    }

}
